mod utils;
mod task;

extern crate cfg_if;
extern crate wasm_bindgen;

use std::collections::BinaryHeap;
use cfg_if::cfg_if;
use wasm_bindgen::prelude::*;
use std::io;
use std::ops::Add;
use std::sync::atomic::AtomicIsize;
use web_sys::{window, Document, HtmlCanvasElement, CanvasRenderingContext2d, js_sys};
use wasm_bindgen::{JsCast, JsObject};
use crate::task::{PriorityLevel, Task};

cfg_if! {
    if #[cfg(feature = "wee_alloc")] {
        extern crate wee_alloc;
        #[global_allocator]
        static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
    }
}
// 定义一个全局的原子计数器
static GLOBAL_ID: AtomicIsize = AtomicIsize::new(0);
pub type CallBack = js_sys::Function;
#[wasm_bindgen]
pub fn scheduler(level: i16, delay: i64, callback: CallBack) -> Result<(), JsValue> {
    // 执行最小堆队列
    let mut min_queue = BinaryHeap::new();
    // 过时最小堆队列
    let mut timer_min_queue = BinaryHeap::new();
    let current_time = utils::get_current_time();
    let start_time = current_time + delay;
    let timeout = match level {
        0 => PriorityLevel::NoPriority.get_timeout(),
        1 => PriorityLevel::ImmediatePriority.get_timeout(),
        2 => PriorityLevel::UserBlockingPriority.get_timeout(),
        3 => PriorityLevel::NormalPriority.get_timeout(),
        4 => PriorityLevel::LowPriority.get_timeout(),
        5 => PriorityLevel::IdlePriority.get_timeout(),
        _ => PriorityLevel::NoPriority.get_timeout()
    };
    let expiration_time = start_time + timeout;
    // 创建任务
    // // callback.call1(&JsValue::NULL, )?;
    let id = GLOBAL_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
    let new_task = Task{
        id,
        callback,
        priority: level,
        start_time,
        expiration_time,
        sort_index: -1
    };
    if(start_time > current_time) {

    }
    Ok(())
}